package com.clever.auth.controller;

import com.clever.auth.dto.NormalLoginRequestParam;
import com.clever.commons.exception.BaseException;
import com.clever.commons.exception.StatusCode;
import com.clever.commons.result.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ChenWang
 * @date 2020/12/14 00:27
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {


    @PostMapping("/login")
    public BaseResult<String> login(@RequestBody NormalLoginRequestParam normalloginRequestParam) {
        UsernamePasswordToken token = new UsernamePasswordToken(
                normalloginRequestParam.getName(), normalloginRequestParam.getPassword());
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            log.info("登陆成功");
        } catch (AccountException e) {
            log.info("账号异常");
//            throw new AccountException("");
            throw new BaseException(StatusCode.ACCOUNT_LOGIN_ERROR);
        } catch (IncorrectCredentialsException e) {
            log.info("账号密码错误");
            throw new BaseException(StatusCode.ACCOUNT_LOGIN_ERROR);
        } catch (Exception e) {
            log.info("系统错误");
            throw new BaseException(StatusCode.SYSTEM_INNER_ERROR);
        }
        //判定是否验证
        if (SecurityUtils.getSubject().isAuthenticated()) {
            String id = SecurityUtils.getSubject().getSession().getId().toString();
            return BaseResult.success(id);
        } else {
            throw new BaseException(StatusCode.PERMISSION_NO_ACCESS);
        }
    }

}
